from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from .models import Question, Choice
from django.urls import reverse
from django.db.models import F
# Create your views here.

def index(request):
    # return HttpResponse("Hello, world. You're at the")
    # results = Question.objects.order_by("-pub_date").all()
    # questions = ",".join([q.question_text for q in results])
    # return HttpResponse(questions)
    questions = Question.objects.order_by('-pub_date')[:5]
    context = {'questions': questions}
    return render(request, 'polls/index.html', context)


def detail(request, question_id):
    # return HttpResponse(f"你选择的是内容是：{question_id}")
    # try:
    #     question = Question.objects.get(pk = question_id)
    # except Question.DoesNotExist:
    #     raise Http404('查无记录')
    # return render(request, 'detail.html', {'question': question})
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
    # response = "你看到所有记录是 %s"
    # return HttpResponse(response % question_id)
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/results.html", {"question": question})

def vote(request, question_id):
    # return HttpResponse("你投票是第%s条记录" % question_id)
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except(KeyError, Choice.DoesNotExist):
        return render(request,
                      'polls/detail.html',
                      {
                          "question": question,
                          "error_message": "没有你要的投票记录",
                      }, status=400)
    else:
        selected_choice.votes = F("votes") + 1
        selected_choice.save()
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))
